package net.oschina.app.ui.fragments;

import net.oschina.app.R;
import net.oschina.app.bean.SearchList;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;

public class SearchViewPagerFragment extends
		BaseViewPagerFragment<BaseListFragment> implements
		SearchView.OnQueryTextListener {
	private SearchView mSearchView;
	private String curSearchContent;
	private BaseSearchListFragment curSearchListFragment;

	public SearchViewPagerFragment(Context context) {
		super();
		titleList.add(context.getString(R.string.frame_title_software));
		titleList.add(context.getString(R.string.frame_title_question));
		titleList.add(context.getString(R.string.frame_title_blog));
		titleList.add(context.getString(R.string.frame_title_news));

		fragmentList.add(new BaseSearchListFragment(
				SearchList.CATALOG_SOFTWARE, this));
		fragmentList.add(new BaseSearchListFragment(SearchList.CATALOG_POST,
				this));
		fragmentList.add(new BaseSearchListFragment(SearchList.CATALOG_BLOG,
				this));
		fragmentList.add(new BaseSearchListFragment(SearchList.CATALOG_NEWS,
				this));
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		mSearchView = new SearchView(getActivity());
		mSearchView.setIconifiedByDefault(false);
		mSearchView.setOnQueryTextListener(this);
		TextView textView = (TextView) mSearchView
				.findViewById(org.holoeverywhere.R.id.search_src_text);
		if (textView != null)
			textView.setTextColor(Color.WHITE);
		MenuItem item = menu.add(R.string.main_menu_search);
		MenuItemCompat.setActionView(item, mSearchView);
		MenuItemCompat.setShowAsAction(item,
				MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
	}

	@Override
	public void onPageSelected(int arg0) {
		curSearchListFragment = (BaseSearchListFragment) fragmentList.get(arg0);
		curSearchListFragment.setCurSearchContent(curSearchContent);
		curSearchListFragment.showList();
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		curSearchContent = query;
		if (curSearchListFragment != null) {
			curSearchListFragment.setCurSearchContent(curSearchContent);
			curSearchListFragment.showList();
		}
		return false;
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		return false;
	}

	@Override
	public void onBaseListFragmentResume(BaseListFragment baseListFragment) {
		if (!isHasBaseListFragmentResumed()) {
			curSearchListFragment = (BaseSearchListFragment) baseListFragment;
			curSearchListFragment.setCurSearchContent(curSearchContent);
			curSearchListFragment.showList();
			setHasBaseListFragmentResumed(true);
		}
	}
}
